import request from '@/common/vmeitime-http';
import { useUserInfoStore, useIndexStore } from '@/store/index';
import { getUserInfo } from '@/common/api/user';
import { getUploadImageParams } from "@/common/api/api";
// import { secAdviserUploadDistParams } from '@/common/api/second-adviser';

/**
 * 验证是否有token，
 * 先获取token，再调用登录接口,根据登录接口判断is_login是否为true,为true,再调用户信息接口,false不调用
*/
export function check_and_login(callback) {
    if (check_token()) {
        callback && callback()
    } else {
        request.getToken().then(info => {
            callback && callback()
        })
    }
}

//验证token
export function check_token() {
    let token = uni.getStorageSync('token');
    if (token && token.token && (new Date()).getTime() < token.expire + token.created) {
        return token.token;
    }
    return false;
}


//验证用户信息,如果没有就获取并且更新
export async function checkUpdateUserInfo() {
    const userInfoStore = useUserInfoStore();
    if(userInfoStore.userInfo.id) return;
    try {
        const res = await getUserInfo();
        if(res.status === 0){
            userInfoStore.setUserInfo(res.detail);
            uni.setStorage({
                key: 'userInfo',
                data: res.detail
            });
        }
    } catch (error) {
        console.error('Check user info failed:', error);
    }
}

/**
 * 验证上传参数根据type
 * @param {String} type 上传参数类型,secAdviser:二手房顾问;seller:新房顾问;public:公共;im:聊天;task:顾问上传任务;business:对二手房中介打分图片
*/
export async function checkUploadParamsByType(type) {
    const indexStore = useIndexStore();
    const uploadParam = indexStore.uploadParam[type];
    let res = {};

    //如果有并且时间没过期就返回该参数
    if(uploadParam && (uploadParam.createdTime + uploadParam.expires*1000 - 300000) > new Date().getTime()) return uploadParam;

    // if(type === 'secAdviser'){
    //     res = await secAdviserUploadDistParams();
    // }

    if(type === 'seller' || type === 'public' || type === 'im' || type === 'task' || type === 'business'){
        res = await getUploadImageParams(type);
    }

    if(res.status !== 0){
        uni.showToast({
            title: res.detail,
            icon: 'none'
        });
        return;
    }
    indexStore.setUploadParam({
        ...res.detail,
        paramType: type,
        createdTime: new Date().getTime()
    });
}